package task;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.sql.SQLException;
import java.util.Map;

import org.eclipse.swt.graphics.ImageData;

import db.util.DbStructure;
import db.util.DbTypeColumnComparator;
import db.util.StringTree;
import db.util.XmlIO;



public class CompareSchemas extends DbTask {
	

	@Override
	public void doRun(Map<String, String> props) throws SQLException {
		String schemaA = props.get("schemaA");
		String schemaB = props.get("schemaB");
		String infileName = props.get("inFile");
		
		DbStructure structureA = null;
		if (schemaA != null && schemaA.trim().length()>0) {
			structureA = DbStructure.create(conn(), dbType, schemaA);
		}
		DbStructure structureB = null;
		if (schemaB != null && schemaB.trim().length()>0) {
			structureB = DbStructure.create(conn(), dbType, schemaB);
		}
		DbStructure structureC = null;
		if (infileName != null && infileName.trim().length()>0) {
			File inFile = new File(infileName);
			try {
				FileReader is = new FileReader(inFile);
				structureC = XmlIO.fromXML(is);
				is.close();
			} catch (IOException e) {
				throw new RuntimeException(e);
			}
		}
		if (structureC != null) {
			if (structureB == null) {
				structureB = structureC;
			} else if (structureA == null) {
				structureA = structureC;
			}
		}
		if (structureA == null || structureB == null) {
			System.out.printf("At least two of schemaA, schemaB and inFile, must have valid values%n");
		} else {
			StringTree os = new StringTree();
			DbTypeColumnComparator cmp = new DbTypeColumnComparator(structureA.getDbType(), structureB.getDbType());
			boolean result = structureA.equals(structureB, os, cmp);
			System.out.printf("Result of comparison: %s%n%n%s%n", result, os.toString());
		}
	}

	@Override
	public String getDescription() {
		String desc = "Compare two schemas";
		return desc;
	}

	@Override
	public ImageData getImageData() {
		// TODO Auto-generated method stub
		return null;
	}

	@Override
	public String[] propertyNames() {
		String[] props = { "schemaA", "schemaB", "inFile" };
		return props;
	}
}
